import { memo } from 'react'
import TableContentStyle from './style'
import { Table } from 'antd'
import { mergeRenders } from './index'
import type { IProps } from './type'

const TableContent = memo(<RecordType extends object>(props: IProps<RecordType>) => {
	const { tableName, toolbars, columns = [], renders, index, pagination } = props

	const newColumns = mergeRenders<RecordType>(columns, renders)
	// 是否插入‘序号’列
	if (index && newColumns) {
		newColumns.unshift({
			title: '序号',
			key: 'index',
			dataIndex: 'index',
			width: 70,
			align: 'center',
			render: (_v, _r, index) => {
				// 有分页时根据页码计算序号，没有则正常排序
				if (pagination && pagination.current && pagination.pageSize) {
					return (pagination.current - 1) * pagination.pageSize + index + 1
				} else {
					return index + 1
				}
			}
		})
	}

	return (
		<TableContentStyle>
			{(tableName || toolbars) && (
				<div className="toolbars">
					<span className="title">{tableName}</span>
					{toolbars && <div className="tools_btns">{toolbars}</div>}
				</div>
			)}
			<Table {...props} columns={newColumns} pagination={pagination ?? false} />
		</TableContentStyle>
	)
}) as <T>(props: IProps<T>) => JSX.Element

export default TableContent
